package service

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"distributed/registry"
)

func Start(
	ctx context.Context, reg registry.Registration, addr string, registerHandler func(),
) (context.Context, error) {
	registerHandler()
	ctx = startService(ctx, reg, addr)
	if err := registry.RegisterService(reg); err != nil {
		return ctx, err
	}
	return ctx, nil
}

func startService(
	ctx context.Context, reg registry.Registration, addr string,
) context.Context {
	ctx, cancel := context.WithCancel(ctx)

	var svr http.Server
	svr.Addr = addr

	go func() {
		log.Println(svr.ListenAndServe())
		shutdownService(reg, cancel)
	}()

	go func() {
		fmt.Printf("%s started. Press any to stop. \n", reg.ServiceName)
		var input string
		fmt.Scanln(&input)
		svr.Shutdown(ctx)
		shutdownService(reg, cancel)
	}()

	return ctx
}

func shutdownService(reg registry.Registration, cancel context.CancelFunc) {
	err := registry.ShutdownService(reg.ServiceURL)
	if err != nil {
		log.Printf("%s服务注销失败: %v", reg.ServiceName, err)
	}
	cancel()
}
